<?php

namespace App\Http\Controllers\Admin;


use App\Models\News;
use App\Validate\NewsValidate;
use Illuminate\Support\Facades\DB;

/**
 * 新闻
 */
class NewsController extends CommonController
{

    public $model = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = new News();
        $this->validate = new NewsValidate();
    }


    /**
     * 列表
     * @param page int 当前页
     * @param limit int 分页大小
     * @param keywords string 搜索关键词(文章标题)
     * @param type_id int 类型id
     * @param start_time int 开始时间
     * @param end_time int 结束时间
     */
    public function lists()
    {
        $page = request()->page ? intval(request()->page) : 1;
        $limit = request()->limit ? intval(request()->limit) : 10;
        $keyword = request()->keywords;
        $type_id = request()->type_id;
        $start_time = request()->start_time;
        $end_time = request()->end_time;

        $condition[] = ['is_del', '=', 1];

        if ($keyword) {
            $condition[] = ['title', 'like', "%$keyword%"];
        }
        if ($type_id) {
            $condition[] = ['type_id', '=', $type_id];
        }
        if ($start_time && $end_time) {
            $condition[] = ['add_time', '>=', $start_time];
            $condition[] = ['add_time', '<=', $end_time];
        }


        $res = $this->model
            ->select('id', 'type_id', 'img', 'title', 'browse_num', 'add_time','create_time', 'change_time', 'content','is_top')
            ->with('conType')
            ->orderByRaw('is_top desc')
            ->orderByRaw('add_time desc')
            ->where($condition)
            ->paginate($limit);

        if ($res->isEmpty()) {
            return $this->returnApi(203, "暂无数据");
        }

        $index_key = $this->list_index_key; //序号标签
        foreach ($res as $key => $value) {
            $res[$key]->$index_key = $this->addSerialNumberOne($key, $page, $limit);
            $res[$key]->content = strip_tags($value->content);

            $res[$key]->type_name = $value->conType ? $value->conType->type_name : null;

            unset($res[$key]->conType);
        }

        $res = $this->disPageData($res->toArray());
        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 详情
     * @param id int 文章id
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $res = $this->model->select('id', 'type_id', 'img', 'title', 'browse_num', 'add_time', 'change_time', 'content', 'is_top')->with('conType')->find(request()->id);

        if (!$res) {
            return $this->returnApi(201, "参数传递错误");
        }

        $res->type_name = $res->conType ? $res->conType->type_name : null;

        unset($res->conType);

        return $this->returnApi(200, "查询成功", "YES", $res->toArray());
    }

    /**
     * 新增
     * @param title string 标题 必填
     * @param img string 封面 必填
     * @param type_id string 类型id 必填
     * @param content string 内容 必填
     * @param is_top string 是否置顶   只能置顶3条  1 是  2 否
     * @param add_time datetime 创建时间  用户手动选择的时间
     */
    public function add()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('add')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        if(empty(strip_tags($this->request->content))){
            return $this->returnApi(201, "请输入内容");
        }
        if (empty($this->request->add_time)) {
            $this->request->merge(['add_time' => date('Y-m-d H:i:s')]); //追加到request里面
        } elseif (!strtotime($this->request->add_time) || date('Y-m-d H:i:s', strtotime($this->request->add_time)) != $this->request->add_time) {
            return $this->returnApi(201, "时间格式不正确");
        }

        $is_exists = $this->model->nameIsExists($this->request->title, 'title');

        if ($is_exists) {
            return $this->returnApi(202, "该标题已存在");
        }

        DB::beginTransaction();
        try {
            $data = $this->request->all();
            if(empty($data['img'])){
                unset($data['img']);
            }

            $this->model->add($data);
            if ($this->request->is_top = 1) {
                $this->model->is_top = 4; //只能置顶3个，下面会全部在减少一次，就刚好是 3 了
                $this->model->save();

                $this->model->where('is_top', '>', 0)->decrement('is_top', 1);
            }

            DB::commit();
            return $this->returnApi(200, "新增成功", true);
        } catch (\Exception $e) {

            DB::rollBack();
            return $this->returnApi(202, "新增失败");
        }
    }

    /**
     * 编辑
     * @param id int 书籍id 必传
     * @param title string 标题 必填
     * @param img string 封面 必填
     * @param type_id string 文章类型id 必填
     * @param content string 文章内容 必填
     * @param add_time datetime 创建时间  用户手动选择的时间
     */
    public function change()
    {

        //增加验证场景进行验证
        if (!$this->validate->scene('change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        if(empty(strip_tags($this->request->content))){
            return $this->returnApi(201, "请输入内容");
        }

        if (empty($this->request->add_time)) {
            $this->request->merge(['add_time' => date('Y-m-d H:i:s')]); //追加到request里面
        } elseif (!strtotime($this->request->add_time) || date('Y-m-d H:i:s', strtotime($this->request->add_time)) != $this->request->add_time) {
            return $this->returnApi(201, "时间格式不正确");
        }

        $is_exists = $this->model->nameIsExists($this->request->title, 'title', $this->request->id);

        if ($is_exists) {
            return $this->returnApi(202, "该标题已存在");
        }

        $data = $this->request->all();
        if(empty($data['img'])){
            unset($data['img']);
        }

        $res = $this->model->change($data);

        if (!$res) {
            return $this->returnApi(202, "修改失败");
        }
        return $this->returnApi(200, "修改成功", true);
    }

    /**
     * 删除
     * @param id int 新闻id
     */
    public function del()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('del')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $res = $this->model->del($this->request->id);

        if ($res === true) {
            return $this->returnApi(200, "删除成功", true);
        }
        return $this->returnApi(202, $res);
    }

    /**
     * 置顶与取消置顶
     * @param id 新闻id
     */
    public function topAndCancel()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('top_and_cancel')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        DB::beginTransaction();
        try {
            $msg = $this->model->topAndCancel($this->request->id);
            DB::commit();
            return $this->returnApi(200, $msg."成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, "设置失败");
        }
    }
}
